package com.oceansoft.mobile.econsole.modules.message.util;

import com.oceansoft.mobile.econsole.modules.message.entity.ExceptionCommonBase;
import com.oceansoft.mobile.econsole.modules.message.entity.PushMessage;

import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

public class Utils {
    public static final String MASTER_KEY = "ec755058b752590cb570a0dc";
    private static int no = 123;

    public static int getCurrNo() {
        return no++;
    }

    public static boolean stringIsNullOrEmpty(String string) {
        return (string == null) || (string.trim().length() < 1) || ("null".equals(string));
    }

    public static boolean stringIsNullOrEmptyOrUndefined(String string) {
        return (string == null) || (string.trim().length() < 1) || ("null".equals(string)) || ("undefined".equalsIgnoreCase(string));
    }

    public static int toInt(String val, int defaultValue) {
        return 0;
    }

    public static boolean stringIsEndWith(String line, String prifx) {
        return !((stringIsNullOrEmpty(line)) || (stringIsNullOrEmpty(prifx))) && line.trim().endsWith(prifx.trim());
    }

    public static String Md5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte[] b = md.digest();
            StringBuilder buf = new StringBuilder("");
            for (byte aB : b) {
                int i = aB;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String http(String urlStr, String method, String bearer, String data) throws ExceptionCommonBase {
        HttpURLConnection conn = null;
        BufferedReader in = null;
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod(method);
            String charset = "UTF-8";
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + charset);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1");
            conn.setRequestProperty("Accept-Language", "zh-CN");
            System.setProperty("http.keepAlive", "false");
            if (!stringIsNullOrEmpty(bearer)) {
                conn.setRequestProperty("Bearer", bearer);
            }
            conn.setUseCaches(false);
            if (!stringIsNullOrEmpty(data)) {
                conn.setDoOutput(true);
                int dataLength = data.getBytes().length;
                conn.setRequestProperty("Content-Length", String.valueOf(dataLength));
                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), charset);
                out.write(data);
                out.flush();
                out.close();
            }
            if (conn.getResponseCode() != 200) {
                conn.disconnect();
                throw new ExceptionCommonBase(-1, "HttpStatus:" + conn.getResponseCode());
            }
            String result = "";
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                result = result + line + "\n";
            }
            return result;
        } catch (Exception ex) {
            throw ExceptionCommonBase.throwExceptionCommonBase(ex);
        } catch (Error e) {
            throw new ExceptionCommonBase(-1);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (conn != null)
                conn.disconnect();
        }
    }

    public static String httpGet(String urlStr, String bearer) throws ExceptionCommonBase {
        return http(urlStr, "GET", bearer, null);
    }

    public static String httpPost(String url, String bearer, Map<String, Object> params) throws ExceptionCommonBase, UnsupportedEncodingException {
        String p = toParams(params);
        return httpPost(url, bearer, p);
    }

    public static String httpPost(String urlStr, String bearer, String data) throws ExceptionCommonBase {
        return http(urlStr, "POST", bearer, data);
    }

    public static String toParams(Map<String, Object> params) throws UnsupportedEncodingException {
        String param = "";
        for (Object key : params.keySet()) {
            Object v = params.get(key);
            param = param + "&" + URLEncoder.encode((String) key, "UTF-8") + "=" + URLEncoder.encode(String.valueOf(v), "UTF-8");
        }
        return (param.length() > 0) ? param.substring(1) : "";
    }

    public static String toParamFromBean(PushMessage message) {
        String result = "";
        try {
            Field[] fields = message.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                if (!field.getName().equals("serialVersionUID")) {
                    result = result + "&" + field.getName() + "=" + getFieldValue(field, message);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return (result.length() > 0) ? result.substring(1) : "";
    }

    private static String getFieldValue(Field field, Object obj) {
        try {
            Object value = field.get(obj);
            if (value == null) {
                return "";
            }
            return value.toString();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return "";
    }
}